var wechatMsgConstruct = require('./wechatMsgConstruct'); //消息构建器
var config = require('../config/config');
module.exports = function (req, res, next) {
    console.log('签到');
    if (req.wechatMsg.MsgType == "text") {
        switch (true) {
            case /签到/.test(req.wechatMsg.Content):
                console.log('接受命令');
                var newDate = (new Date().getTime())/1000;//秒
                if((newDate - req.wechatUserInfo.check_in_time)>(config.checkinTime*3600)){
                    CheckIn(req, res, next);
                }else {
                    var chat = {
                        Type: "text",
                        Content: "距离上次签到不满"+config.checkinTime+"小时，请稍后再来"
                    };
                    // 最后一步需要信息,并关闭数据库连接
                    req.mysqlConnection.end();
                    res.send(wechatMsgConstruct(req.wechatMsg, chat));
                }
                break;
            default:
                next();
                break;
        }
    } else {
        next()
    }
    function RandomNum(Min, Max) {
        var Range = Max - Min;
        var Rand = Math.random();
        if(Math.round(Rand * Range)==0){
            return Min + 1;
        }else if(Math.round(Rand * Max)==Max)
        {
            index++;
            return Max - 1;
        }else{
            var num = Min + Math.round(Rand * Range) - 1;
            return num;
        }
    }
    function CheckIn(req, res, next) {
        var newTransferEnable = RandomNum(config.checkinMin,config.checkinMax)*1048576;
        var query = req.mysqlConnection.query("UPDATE `" + config.mysql.database + "`.`ss_user` SET `transfer_enable` = '" + (newTransferEnable+req.wechatUserInfo.transfer_enable) + "',`check_in_time` = '" + ((new Date().getTime())/1000) + "' WHERE `ss_user`.`open_id` like '" + req.wechatMsg.FromUserName + "'");//
        query
            .on('error', function (err) {
                console.log('数据库连接失败', err)
            })
            .on('result', function (row) {
                req.mysqlConnectionStatus = true ;
            })
            .on('end', function () {
                if ( req.mysqlConnectionStatus = true ){
                    var chat = {
                        Type: "text",
                        Content: "签到成功，获得"+newTransferEnable/1048576+"M流量"
                    };
                    // 最后一步需要信息,并关闭数据库连接
                    req.mysqlConnection.end();
                    res.send(wechatMsgConstruct(req.wechatMsg, chat));
                }else {
                    var chat = {
                        Type: "text",
                        Content: "签到失败，原因不知道，联系管理员看看"
                    };
                    // 最后一步需要信息,并关闭数据库连接
                    req.mysqlConnection.end();
                    res.send(wechatMsgConstruct(req.wechatMsg, chat));
                }

            });
    }

};